﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ParkingLot.Utility
{
    public static class EnumHelp
    {
        /// <summary>
        /// 获取枚举类型的详细内容
        /// </summary>
        /// <typeparam name="TEnum"></typeparam>
        /// <returns></returns>
        public static List<TEnum> GetAllEnumValues<TEnum>()where TEnum:struct
        {
            Type type = typeof (TEnum);
           List<TEnum> lisEnumValue=new List<TEnum>();

            //目前C#还不支持泛型约束 但是c++已经支持 等C#支持枚举约束即可修改此处
            if (!type.IsEnum)
            {
                return lisEnumValue;
            }

            foreach (int i in Enum.GetValues(typeof(TEnum)))
            {
                object obj= Convert.ChangeType(i, typeof(object));
                TEnum tEnum = (TEnum)obj;
                lisEnumValue.Add(tEnum);
            }
            return lisEnumValue;
        }

        public static string GetDescription(this Enum obj)
        {
            return GetDescription(obj, false);
        }

        private static string GetDescription(this Enum obj, bool isTop)
        {
            if (obj == null)
            {
                return string.Empty;
            }
            try
            {
                Type _enumType = obj.GetType();
                DescriptionAttribute dna = null;
                if (isTop)
                {
                    dna = (DescriptionAttribute)Attribute.GetCustomAttribute(_enumType, typeof(DescriptionAttribute));
                }
                else
                {
                    FieldInfo fi = _enumType.GetField(Enum.GetName(_enumType, obj));

                    dna = (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute));
                }
                if (dna != null && string.IsNullOrEmpty(dna.Description) == false)
                    return dna.Description;
            }
            catch
            {
                return string.Empty;
            }
            return obj.ToString();
        }

        /// <summary>
        /// 获取枚举类型的详细内容
        /// </summary>
        /// <typeparam name="TEnum"></typeparam>
        /// <returns></returns>
        public static List<Enum> GetAllEnumValues(this Enum enumType) 
        {
            Type type = enumType.GetType();
            List<Enum> lisEnumValue = new List<Enum>();

            //目前C#还不支持泛型约束 但是c++已经支持 等C#支持枚举约束即可修改此处
            if (!type.IsEnum)
            {
                return lisEnumValue;
            }

            foreach (int i in Enum.GetValues(type))
            {
                object obj = Convert.ChangeType(i, typeof(object));
                Enum tEnum = (Enum)obj;
                lisEnumValue.Add(tEnum);
            }
            return lisEnumValue;
        }


    }
}
